using System;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using System.Data;

namespace IPAMS.Views
{
    /// <summary>
    /// This is an editor for the CurrencyExchangeRates table. It enables loading from a file,
    ///saving to a file and more
    /// </summary>
    public partial class CurrencyExchangeRatesEditor : UserControl
    {
        public DSIPAMS.DTCurrencyExchangeRateDataTable currencyExchangeRates;
        string[] currenciesExchangeRatesHeaders;

        /// <summary>
        /// Initializes a new instance of the <see cref="CurrencyExchangeRatesEditor"/> class.
        /// </summary>
        public CurrencyExchangeRatesEditor()
        {
            InitializeComponent();
            InitializeComponentExtended();
        }

        /// <summary>
        /// Initializes the component extended.
        /// </summary>
        private void InitializeComponentExtended()
        {
            currencyExchangeRates = new DSIPAMS.DTCurrencyExchangeRateDataTable();
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the comboBoxSelectCurrency control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void comboBoxSelectCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            string from = comboBoxSelectOriginalCurrency.SelectedItem != null &&
                          comboBoxSelectOriginalCurrency.SelectedItem.ToString() != string.Empty
                              ? string.Format("= '{0}'", comboBoxSelectOriginalCurrency.SelectedItem)
                              : "LIKE '*'";
            string to = comboBoxSelectTargetCurrency.SelectedItem != null &&
                        comboBoxSelectTargetCurrency.SelectedItem.ToString() != string.Empty
                            ? string.Format("= '{0}'", comboBoxSelectTargetCurrency.SelectedItem)
                            : "LIKE '*'";


            string expression =
                string.Format(
                    "CURRENCY_EXCHANGE_RATE_FROM_SYMBOL {0} AND CURRENCY_EXCHANGE_RATE_TO_SYMBOL {1}", from, to);
            string sorting = "CURRENCY_EXCHANGE_RATE_DATE ASC";

            dgvCurrenciesExchangeRates.DataSource = currencyExchangeRates.Select(expression, sorting);
        }

        /// <summary>
        /// Handles the DataSourceChanged event of the dgvCurrenciesExchangeRates control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void dgvCurrenciesExchangeRates_DataSourceChanged(object sender, EventArgs e)
        {
            dgvCurrenciesExchangeRates.Refresh();
        }

        /// <summary>
        /// Loads the data from a file.
        /// </summary>
        /// <param name="dataFilePath">The data file path.</param>
        /// <returns>a DataTable with the file's data</returns>
        public DataTable LoadData(string dataFilePath)
        {
            currencyExchangeRates = new DSIPAMS.DTCurrencyExchangeRateDataTable();


            if (File.Exists(dataFilePath))
            {
                StreamReader sr = new StreamReader(dataFilePath);
                currenciesExchangeRatesHeaders = sr.ReadLine().Split(',');;
                while (true)
                {
                    string currencyExchangeRate = sr.ReadLine();
                    if (currencyExchangeRate == string.Empty || currencyExchangeRate == null) break;
                    string[] currencyExchangeRateInfo = currencyExchangeRate.Split(',');
                    if (currencyExchangeRateInfo.Length != 4) continue;
                    CultureInfo ci = new CultureInfo("he-IL");
                    
                    currencyExchangeRates.AddDTCurrencyExchangeRateRow(DateTime.Parse(currencyExchangeRateInfo[0],ci.DateTimeFormat), currencyExchangeRateInfo[1], Convert.ToDouble(currencyExchangeRateInfo[2]), currencyExchangeRateInfo[3]);
                }
                sr.Close();

                Text = dataFilePath;
                currencyExchangeRates.AcceptChanges();

                dgvCurrenciesExchangeRates.DataSource = currencyExchangeRates;
                for (int index = 0; index < currenciesExchangeRatesHeaders.Length; index++)
                {
                    dgvCurrenciesExchangeRates.Columns[index].HeaderText = currenciesExchangeRatesHeaders[index];
                }

                foreach (DataGridViewColumn column in dgvCurrenciesExchangeRates.Columns)
                {
                    column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }

            }


            return currencyExchangeRates;
        }

        /// <summary>
        /// Saves the data to a file.
        /// </summary>
        /// <param name="dataFilePath">The data file path.</param>
        public void SaveData(string dataFilePath)
        {
            StreamWriter sw = new StreamWriter(dataFilePath);
            string fileContent = currenciesExchangeRatesHeaders + Environment.NewLine;
            foreach (DSIPAMS.DTCurrencyExchangeRateRow currencyExchangeRate in currencyExchangeRates)
            {
                fileContent += string.Format("{0},{1},{2},{3}" + Environment.NewLine, currencyExchangeRate[0], currencyExchangeRate[1], currencyExchangeRate[2], currencyExchangeRate[3]);
            }
            sw.Write(fileContent);
            sw.Close();

        }

    }
}
